<?php
namespace App\Http\Controllers\Admin;

use App\Business;
use App\Http\Controllers\Controller;
use App\User;
use App\UserCoinLog;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Intervention\Image\Facades\Image;


class HomeController extends Controller
{
    public function index(Request $request)
    {
        $data = [];

        $query = UserCoinLog::orderBy('created_at', 'desc');

        if ($request->has('type')) {
            switch ($request->input('type')) {
                case 'charge':
                    $query->where('coin', '>', 0)->where('bussiness_id', 0);
                    break;

                case 'change':
                    $query->where('coin', '<', 0)->where('bussiness_id', 0);
                    break;

                default:
                    # code...
                    break;
            }
        }

        $logs = $query->paginate(15);

        $bussiness[] = '-';
        foreach (Business::get() as $item) {
            $bussiness[] = $item->name;
        }

        $data['logs'] = $logs;
        $data['params'] = $request->all();
        $data['bussiness'] = $bussiness;

        $request->flash();

        return view('admin.index', $data);
    }

    public function user_list(Request $request)
    {
        $data = [];

        $query = User::orderBy('created_at', 'asc')->select(['id', 'nickname', 'avatar', 'created_at', 'status', 'openid', 'openid_app', 'phone']);

        if ($request->has('nickname')) {
            $query->where('nickname', 'like', $request->input('nickname'));

            if ($query->count() > 10) {
                $data['error'] = '搜索结果大于10，请重新搜索';
            } else {
                $data['users'] = $query->get();
            }
        }

        $request->flash();

        return view('admin.user_list', $data);
    }

    /**
     * 统计用户当前七点到用户下APP等
     * @return mixed
     */
    public function userAll()
    {
        $data = [];
        $time = Carbon::today()->format('Y-m-d') . ' 19:00:00';
        $users = User::whereIn('id', function ($query) use ($time) {
            $query->selectRaw('DISTINCT(finder_id)')
                ->from('user')
                ->whereRaw("status7_at>=" . "'$time'" . " and finder_id<>0");
        })->get();
        
        $data['users'] = $users;
        $data['time'] = $time;
        return view('admin.user_all', $data);
    }

    public function user_vip_cancel(Request $request)
    {
        $user = User::find($request->input('id'));

        $gameZghpt = $user->game_zghpt;
        $gameZghpt->level = 0;
        $gameZghpt->save();

        return response()->json(['status' => 'success']);
    }

    public function user(Request $request)
    {
        $query = User::orderBy('created_at', 'desc');

        $user = User::find($request->input('id'));
        $users = $query->where('finder_id', $request->input('id'))->paginate(15);

        $user->XYB = UserCoinLog::totalXyb($user->id);
        $user->JB = UserCoinLog::totalJb($user->id);

        $data['user'] = $user;
        $data['users'] = $users;
        $data['params'] = $request->all();
        $data['valid_count'] = $user->fans()->where('status', 7)->count();

        $request->flash();

        return view('admin.user', $data);
    }

    public function hldy(Request $request)
    {
        $total = UserCoinLog::where('bussiness_id', 2)->sum('coin');
        return 'total:' . $total;
    }

    public function vip()
    {
        $users = DB::select("select u.nickname,f.c from (select `finder_id` id,count(`finder_id`) c from `user` where `id` in (select `user_id` from `order` where `status`=1 and `product_id`=1 and `created_at`>='2017-02-07 18:00:00' and `created_at`<'2017-02-08 00:00:00') group by `finder_id`) f left join `user` u on f.`id`=u.`id` order by f.`c` desc");

        echo '<table border="1"><tr><th>昵称</th><th>个数</th></tr>';
        foreach ($users as $user) {
            if ($user->nickname) {
                echo '<tr><td>' . $user->nickname . '</td><td>' . $user->c . '</td></tr>';
            }
        }
        echo '</table>';
    }

    /**
     * 欢乐钓鱼
     */
    public function fish()
    {
        echo '<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">';

        $fish_list = ['15' => '旗鱼', '16' => '厚唇鱼', '17' => '鲨鱼', '10' => '一杠10鱼', '8' => '一杠8鱼', '6' => '一杠6鱼'];
        $userArr = [];

        //一杠几鱼计算
        $numb_list = DB::table('pan_fishing as f')
            ->leftJoin('user', 'user.id', '=', 'f.mid')
            ->select('user.nickname', 'user.id as uid', 'f.created_at', 'f.numb')
            ->where('f.created_at', '>=', Carbon::today()->format('Y-m-d') . ' 16:00:00')
            ->whereIn('f.numb', [10, 8, 6])
            ->orderBy('f.created_at', 'desc')
            ->get()
            ->toArray();

        foreach ($numb_list as $key => $val) {
            $userArr[$val->uid]['nickname'] = $val->nickname;
            $data['created_at'] = $val->created_at;
            $data['fish_id'] = $val->numb;
            $userArr[$val->uid]['desc'][] = $data;
            unset($data, $val);
        }

        //鱼类施计算
        $users = DB::table('pan_fishing_item as f')
            ->leftJoin('user', 'user.id', '=', 'f.mid')
            ->select('user.nickname', 'user.id as uid', 'f.created_at', 'f.fish_id')
            ->where('f.created_at', '>=', Carbon::today()->format('Y-m-d') . ' 16:00:00')
            ->whereIn('f.fish_id', [5, 6, 7])
            ->orderBy('f.created_at', 'desc')
            ->get()
            ->toArray();

        foreach ($users as $key => $val) {
            $userArr[$val->uid]['nickname'] = $val->nickname;
            $data['created_at'] = $val->created_at;
            $data['fish_id'] = 10 + $val->fish_id;
            $userArr[$val->uid]['desc'][] = $data;
            unset($data, $val);
        }

        foreach ($userArr as $key => $value) {

            echo '<h1>昵称:' . $value['nickname'] . '</h1><table class="table table-bordered"><tr><th>顺序</th><th>鱼类</th><th>时间</th></tr>';
            $i = 1;
            echo '<thend></thend>';
            array_multisort(array_column($value['desc'], 'fish_id'), SORT_DESC, $value['desc']);

            foreach ($value['desc'] as $user) {
                echo '<tr><td>' . $i . '</td><td>' . $fish_list[$user['fish_id']] . '</td><td>' . $user['created_at'] . '</td></tr>';
                $i++;
            }
            echo '</table>';
        }
    }

    /**
     * 水果大作战
     */
    public function sgdzz()
    {
        echo '<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">';
        $sg = [1 => '菠萝', 2 => '香蕉', 3 => '苹果'];
        $logs = DB::table('game_sgdzz_order_detail_log as l')
            ->join('user', 'user.id', '=', 'l.user_id')
            ->select('user.nickname', 'user.id as uid', 'l.issue', 'l.gold', 'l.created_at', 'l.type')
            ->where('l.is_win', 1)
            ->where('l.created_at', '>=', Carbon::today()->format('Y-m-d') . ' 16:00:00')
            ->whereIn('l.type', [1, 2, 3])
            ->orderBy('l.created_at', 'desc')
            ->get()
            ->toArray();

        $logArr = [];
        foreach ($logs as $key => $val) {
            $logArr[$val->uid]['nickname'] = $val->nickname;
            $data['created_at'] = $val->created_at;
            $data['issue'] = $val->issue;
            $data['gold'] = $val->gold;
            $data['type'] = $val->type;
            $logArr[$val->uid]['desc'][] = $data;
            unset($data, $val);
        }

        foreach ($logArr as $key => $value) {

            echo '<h1>昵称:' . $value['nickname'] . '</h1><table class="table table-bordered"><tr><th>水果</th><th>期数</th><th>金额</th><th>时间</th></tr>';
            foreach ($value['desc'] as $log) {
                echo '<tr><td>' . $sg[$log['type']] . '</td><td>' . $log['issue'] . '</td><td>' . $log['gold'] . '</td><td>' . $log['created_at'] . '</td></tr>';
            }
            echo '</table>';
        }
    }

    public function jyb()
    {
        echo '<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">';

        $JYBs = DB::select("SELECT u.nickname,t.c FROM (SELECT uid,count(1) c FROM `game_jbp_user_yb` j WHERE `origin_type`='qb' AND created_time>='" . Carbon::today()->format('Y-m-d') . "' GROUP BY `uid`) t LEFT JOIN `user` u ON t.uid=u.id");

        echo '<table class="table table-bordered"><tr><th>昵称</th><th>数量</th></tr>';
        foreach ($JYBs as $JYB) {
            echo '<tr><td>' . $JYB->nickname . '</td><td>' . $JYB->c . '</td></tr>';
        }
        echo '</table>';
    }

    public function sgdzz_total()
    {
        $data = DB::select("SELECT SUM(coin) s FROM `user_coin_log` WHERE type=1 AND bussiness_id=5");
        $data = json_decode(json_encode($data), true);

        return response()->view('layouts.message', ['message' => '水果大作战收入：' . -$data[0]['s']], 200);
    }

    /**
     * 添加机器人
     *
     * @param  [type] $request [description]
     * @return [type]          [description]
     */
    public function cq(Request $request)
    {
        $nickname = $request->input('nickname');
        $file = $request->file('file');


        if (empty($nickname)) {
            return view('admin.cq');
        }

        $data = [
            'nickname' => $nickname,
            'avatar' => '',
            'XYB' => rand(8000, 67000) / 100,
            'JB' => rand(8000, 67000) / 100,
        ];
        $id = DB::table('robot')->insertGetId($data);
        $path = '/upfiles/avatar/r' . $id . '.png';
        Image::make($file)->save(public_path($path));
        DB::table('robot')->where('robot_id', $id)->update(['avatar' => $path]);
        if (!empty($id) && intval($id) > 0) {
            echo "保存成功";
        } else {
            echo "保存失败";
        }

    }
}

